package main

import (
	"flag"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"os"
	"path/filepath"
)

func main() {
	var err error
	var config *rest.Config // rest config就是访问k8s api的配置对象

	var kubeconfig *string

	if home := homeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, "kube", "config"), "(可选), kubeconfig文件绝对路径")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "kubeconfig文件绝对路径")
	}
	flag.Parse()

	// 首先用InCluster模式， rest.InClusterConfig() 取pod内置的配置
	if config, err = rest.InClusterConfig(); err != nil {
		// 使用kubeconfig 文件创建集群配置 Config对象
		if config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig); err != nil {
			panic(err.Error())
		}
	}

	// 已经获得了 Config 对象
	// 创建ClientSet 对象
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// 就可以使用Clientset 对象获取资源对象， 进行CRUD
	deployments, err := clientset.AppsV1().Deployments("default").List(metav1.ListOptions{})
	if err != nil {
		panic(err.Error())
	}
	for idx, deploy := range deployments.Items {
		fmt.Printf("%d -> %s\n", idx+1, deploy.Name)
	}

}

func homeDir() string {
	if h := os.Getenv("HOME"); h != "" {
		return h
	}
	return os.Getenv("USERPROFILE") // windows
}
